'use client';

import type { TMetadata } from '@/types';
import { useQuery } from '@tanstack/react-query';
import ErrorPage from '@/app/[locale]/error/error';
import { queryPostNewInfo } from '@/services/api';
import type { IPostNewInfo } from '@/interfaces';
import EditPostCore from '@/app/[locale]/posts/[id]/edit/core';
import LoadPage from '@/app/[locale]/load/load';
import FooterH5IcpPage from '@/app/[locale]/mobile/footerH5Icp';
import FooterH5Page from '@/app/[locale]/mobile/footerH5';

export default function NewPostH5Page({ metadata }: { metadata: TMetadata }) {
  return (
    <>
      <NewPost metadata={metadata} />
      <FooterH5IcpPage metadata={metadata} />
      <FooterH5Page metadata={metadata} />
    </>
  );
}

const NewPost = ({ metadata }: { metadata: TMetadata }) => {
  const queryPostNewInfoQuery = useQuery(
    metadata.all['newPost'].k,
    async () => {
      return (await queryPostNewInfo()) as IPostNewInfo;
    },
    {
      initialData: metadata.all['newPost'].v as IPostNewInfo,
    },
  );

  if (queryPostNewInfoQuery.data) {
    const data = queryPostNewInfoQuery.data;
    return (
      <div className="col p-2">
        <div className="card rounded-5 border-0">
          <div className="card-body">
            <EditPostCore
              type="newPost"
              data={data as any}
              metadata={metadata}
            />
          </div>
        </div>
      </div>
    );
  }

  if (queryPostNewInfoQuery.error) {
    return <ErrorPage error={queryPostNewInfoQuery.error} />;
  }

  return <LoadPage />;
};
